import { useExpose } from '@renderer/utils'
import { defineComponent } from 'vue'
import { ElMessage } from 'element-plus'

export default defineComponent({
  name: 'UploadFile',
  props: {
    state: {
      type: Object,
      default: () => ({
        name: '上传文件',
        type: '.xlsx,.XLSX',
        unit: 'MB',
        size: 10
      })
    }
  },
  emit: ['submit'],
  setup(props, { emit, slots }) {
    const { state } = props
    const handleChange = async (file: any) => {
      const fileName = file.name.split('.')
      if (!state.type.includes(fileName.pop())) {
        ElMessage.error('上传文件类型不正确, 请重新上传!')
        ElMessage.success
        return
      }
      if (state.unit === 'KB') {
        if (file.size / 1024 > state.size) {
          ElMessage.error(`文件大小不能超过${state.size}KB`)
          return
        }
      }
      if (state.unit === 'MB') {
        if (file.size / 1024 / 1024 > state.size) {
          ElMessage.error(`文件大小不能超过${state.size}MB`)
          return
        }
      }
      // console.log('上传文件', res)
    }
    const renderDefault = () => <>{slots.default?.() || <div>{state.name}</div>}</>
    useExpose({
      handleChange
    })
    return () => (
      <el-upload action="" accept={state.type} showFileList={false} autoUpload={false} onChange={handleChange}>
        {{
          default: renderDefault()
        }}
      </el-upload>
    )
  }
})
